<template>
  <div>
    <div class="flex-between mb-16">
      <h2>招聘职位管理</h2>
      <a-button type="primary" @click="handleAdd">
        <PlusOutlined />
        新建职位
      </a-button>
    </div>

    <a-table
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <a-tag :color="record.status === 1 ? 'green' : 'default'">
            {{ record.status === 1 ? '招聘中' : '已关闭' }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
            <a-popconfirm
              title="确定删除这个职位吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="handleDelete(record.id)"
            >
              <a-button type="link" danger size="small">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 新建/编辑弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @ok="handleSubmit"
      @cancel="handleCancel"
      width="900px"
    >
      <a-form :model="formState" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <a-form-item label="职位名称" required>
          <a-input v-model:value="formState.title" placeholder="请输入职位名称" />
        </a-form-item>
        <a-form-item label="部门">
          <a-input v-model:value="formState.department" placeholder="请输入部门" />
        </a-form-item>
        <a-form-item label="工作地点">
          <a-input v-model:value="formState.location" placeholder="请输入工作地点" />
        </a-form-item>
        <a-form-item label="工作类型">
          <a-select v-model:value="formState.job_type" placeholder="请选择工作类型">
            <a-select-option value="全职">全职</a-select-option>
            <a-select-option value="兼职">兼职</a-select-option>
            <a-select-option value="实习">实习</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="薪资范围">
          <a-input v-model:value="formState.salary_range" placeholder="例如：10k-15k" />
        </a-form-item>
        <a-form-item label="经验要求">
          <a-input v-model:value="formState.experience_required" placeholder="例如：3-5年" />
        </a-form-item>
        <a-form-item label="学历要求">
          <a-input v-model:value="formState.education_required" placeholder="例如：本科及以上" />
        </a-form-item>
        <a-form-item label="职位描述">
          <a-textarea v-model:value="formState.description" :rows="3" placeholder="请输入职位描述" />
        </a-form-item>
        <a-form-item label="岗位职责">
          <a-textarea v-model:value="formState.responsibilities" :rows="4" placeholder="请输入岗位职责" />
        </a-form-item>
        <a-form-item label="任职要求">
          <a-textarea v-model:value="formState.requirements" :rows="4" placeholder="请输入任职要求" />
        </a-form-item>
        <a-form-item label="福利待遇">
          <a-textarea v-model:value="formState.benefits" :rows="3" placeholder="请输入福利待遇" />
        </a-form-item>
        <a-form-item label="招聘人数">
          <a-input-number v-model:value="formState.headcount" :min="1" style="width: 100%" />
        </a-form-item>
        <a-form-item label="状态">
          <a-radio-group v-model:value="formState.status">
            <a-radio :value="1">招聘中</a-radio>
            <a-radio :value="0">已关闭</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { getJobs, createJob, updateJob, deleteJob } from '@/api/job'
import type { Job } from '@/types'

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '职位名称', dataIndex: 'title', key: 'title' },
  { title: '部门', dataIndex: 'department', key: 'department', width: 120 },
  { title: '工作地点', dataIndex: 'location', key: 'location', width: 120 },
  { title: '薪资范围', dataIndex: 'salary_range', key: 'salary_range', width: 120 },
  { title: '招聘人数', dataIndex: 'headcount', key: 'headcount', width: 100 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 180 },
  { title: '操作', key: 'action', width: 150 }
]

const dataSource = ref<Job[]>([])
const loading = ref(false)
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

const modalVisible = ref(false)
const modalTitle = ref('新建职位')
const editId = ref<number>()
const formState = reactive<Partial<Job>>({
  title: '',
  department: '',
  location: '',
  job_type: '',
  salary_range: '',
  experience_required: '',
  education_required: '',
  description: '',
  responsibilities: '',
  requirements: '',
  benefits: '',
  headcount: 1,
  status: 1
})

const fetchJobs = async () => {
  loading.value = true
  try {
    const res = await getJobs({
      page: pagination.current,
      page_size: pagination.pageSize
    })
    dataSource.value = res.data.items
    pagination.total = res.data.total
  } catch (error) {
    console.error('获取职位列表失败', error)
  } finally {
    loading.value = false
  }
}

const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchJobs()
}

const handleAdd = () => {
  modalTitle.value = '新建职位'
  editId.value = undefined
  Object.assign(formState, {
    title: '',
    department: '',
    location: '',
    job_type: '',
    salary_range: '',
    experience_required: '',
    education_required: '',
    description: '',
    responsibilities: '',
    requirements: '',
    benefits: '',
    headcount: 1,
    status: 1
  })
  modalVisible.value = true
}

const handleEdit = (record: Job) => {
  modalTitle.value = '编辑职位'
  editId.value = record.id
  Object.assign(formState, {
    title: record.title,
    department: record.department,
    location: record.location,
    job_type: record.job_type,
    salary_range: record.salary_range,
    experience_required: record.experience_required,
    education_required: record.education_required,
    description: record.description,
    responsibilities: record.responsibilities,
    requirements: record.requirements,
    benefits: record.benefits,
    headcount: record.headcount,
    status: record.status
  })
  modalVisible.value = true
}

const handleSubmit = async () => {
  try {
    if (editId.value) {
      await updateJob(editId.value, formState)
      message.success('更新成功')
    } else {
      await createJob(formState)
      message.success('创建成功')
    }
    modalVisible.value = false
    fetchJobs()
  } catch (error) {
    console.error('提交失败', error)
  }
}

const handleCancel = () => {
  modalVisible.value = false
}

const handleDelete = async (id: number) => {
  try {
    await deleteJob(id)
    message.success('删除成功')
    fetchJobs()
  } catch (error) {
    console.error('删除失败', error)
  }
}

onMounted(() => {
  fetchJobs()
})
</script>

<style scoped>
.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.mb-16 {
  margin-bottom: 16px;
}
</style>

